package com.hc.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.hc.api.enums.CommentStateEnum;
import com.hc.api.enums.GoodsEnum;
import com.hc.api.enums.UserDegreeEnum;
import com.hc.api.utils.ApiUtil;
import com.hc.comm.base.BaseController;
import com.hc.comm.dto.CommentDTO;
import com.hc.comm.dto.HospitalDTO;
import com.hc.comm.dto.LikeCommentDTO;
import com.hc.comm.dto.UserdataDTO;
import com.hc.comm.exception.OprationStatus;
import com.hc.comm.utils.CollectionUtils;
import com.hc.comm.utils.JsonUtils;
import com.hc.comm.utils.StringUtil;
import com.hc.comm.vo.CommentVO;
import com.hc.service.model.CommentModel;
import com.hc.service.model.HospitalModel;
import com.hc.service.model.LikeCommentModel;
import com.hc.service.model.UserdataModel;
import com.hc.service.service.ICommentService;
import com.hc.service.service.IHospitalService;
import com.hc.service.service.ILikeCommentService;
import com.hc.service.service.IUserdataService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yx on 2017/4/12.
 * 评论操作
 */
@Controller
@Scope("prototype")
@RequestMapping("/" + ApiUtil.ApiVersion.V1 + "/")
public class CommentController extends BaseController {

    @Resource(name = "userdataService")
    private IUserdataService userdataService;

    @Resource(name = "commentService")
    private ICommentService commentService;

    @Resource(name = "hospitalService")
    private IHospitalService hospitalService;

    @Resource(name = "likeCommentService")
    private ILikeCommentService likeCommentService;

    /**
     * 获取医院的评论列表
     * hostpital_id  医院id
     * page  页数
     */
    @RequestMapping("hospital/comments_lists")
    public void getHospitalCommentList(HttpServletRequest request) throws Exception {
        String hostpital_id = request.getParameter("hostpital_id");
        String page = request.getParameter("page");
        if (StringUtil.isEmpty(hostpital_id) || !StringUtil.isNumeric(hostpital_id)
                || StringUtil.isEmpty(page) || !StringUtil.isNumeric(page)) {
            //writeToJson("参数有误！");
            JsonUtils.toErrorResult(request, response, "参数有误!", OprationStatus.FAIL.getCode());
        } else {
            HospitalDTO hospitalDTO = new HospitalDTO();
            hospitalDTO.setId(Integer.valueOf(hostpital_id));
            HospitalModel hospitalModel = hospitalService.getOne(hospitalDTO);
            if (hospitalModel == null) {
                JsonUtils.toSuccessResult(request, response, "没有该医院的评论!", "");
            } else {
                CommentDTO commentDTO = new CommentDTO();
                commentDTO.setCommentType(GoodsEnum.HOSPITAL.getCode());
                commentDTO.setGoodsId(Integer.valueOf(hostpital_id));
                commentDTO.setCommentState(CommentStateEnum.NORMAL.getCode());
                commentDTO.setCommentId(0);
                commentDTO.setRows(10);
                commentDTO.setPage(Integer.valueOf(page));
                //获取主评论的list
                List<CommentModel> commentList = commentService.getList(commentDTO);
                List<CommentVO> commentVOList = new ArrayList<>();
                for (CommentModel model : commentList) {
                    CommentVO commentVO = new CommentVO();
                    commentVO.copyPropertis(model);
                    commentVOList.add(commentVO);
                }
                List<Integer> commentId = CollectionUtils.getBeanFieldValues(commentList, "id");

                for (int i = 0; i < commentId.size(); i++) {
                    CommentDTO childDto = new CommentDTO();
                    childDto.setCommentId(commentId.get(i));
                    childDto.setRows(20);
                    childDto.setCommentState(CommentStateEnum.NORMAL.getCode());
                    childDto.setSort("createTime");
                    childDto.setPage(1);
                    List<CommentModel> listComment = commentService.getList(childDto);
                    if (listComment != null && listComment.size() > 0) {
                        List<CommentVO> replayList = new ArrayList<>();
                        for (CommentModel comentModel : listComment) {
                            CommentVO commentVo = new CommentVO();
                            commentVo.copyPropertis(comentModel);
                            replayList.add(commentVo);
                        }
                        commentVOList.get(i).setReplayComment(replayList);
                    }
                }
                JsonUtils.toSuccessResult(request, response, commentVOList);
            }
        }

    }

    /**
     * 普通用户对医院进行评论
     * object_type  类型1医院，2优惠券，3订单
     * object_id  医院id
     * user_id  用户id
     * access_token token
     * content 评论类容
     */
    @RequestMapping("comments/hospital")
    public void normalUserComment(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //评论对象类型
        String object_type = request.getParameter("object_type");
        String object_id = request.getParameter("object_id");
        String content = request.getParameter("content");
        String userid = request.getParameter("user_id");
        String access_token = request.getParameter("access_token");
        if (StringUtil.isEmpty(content)
                || (StringUtil.isEmpty(object_id)
                || !StringUtil.isNumeric(object_id))
                || (StringUtil.isEmpty(object_type)
                || !StringUtil.isNumeric(object_type))
                || (GoodsEnum.HOSPITAL.getCode() != Integer.valueOf(object_type))) {
            JsonUtils.toErrorResult(request, response, "参数有误!", OprationStatus.FAIL.getCode());
        } else if (StringUtil.isEmpty(userid) || !StringUtil.isNumeric(userid) || StringUtil.isEmpty(access_token)) {
            JsonUtils.toErrorResult(request, response, "请先登录!", OprationStatus.LOGIN.getCode());
        } else {
            UserdataModel userdataModel = validateUser(Long.valueOf(userid));
            if (userdataModel == null
                    || !access_token.equals(userdataModel.getAppToken())) {
                JsonUtils.toErrorResult(request, response, "请先登录!", OprationStatus.LOGIN.getCode());
            } else {
                CommentModel commentModel = new CommentModel();
                commentModel.setContent(content);
                commentModel.setUserId(Integer.valueOf(userid));
                commentModel.setGoodsId(Integer.valueOf(object_id));
                commentModel.setCommentType(Integer.valueOf(object_type));
                commentModel.setUserDegree(UserDegreeEnum.USER.getCode());
                commentModel.setCommentState(CommentStateEnum.NORMAL.getCode());
                commentModel.setCreateTime((int) System.currentTimeMillis() / 1000);
                commentModel.setUpdateTime((int) System.currentTimeMillis() / 1000);
                commentModel = commentService.insert(commentModel);
                if (commentModel != null) {
                    JsonUtils.toSuccessResult(request, response, "评论成功！", "");
                } else {
                    JsonUtils.toErrorResult(request, response, "评论失败!");
                }
            }

        }
    }

    private UserdataModel validateUser(long userId) throws Exception {
        UserdataDTO userdataDTO = new UserdataDTO();
        userdataDTO.setId(Long.valueOf(userId));
        return userdataService.getOne(userdataDTO);
    }


    /**
     * comment_id 评论的id
     * user_id  用户的id
     * access_token  登录access_token
     * like_state 点赞状态0不点赞，1点赞
     *
     * @param request
     * @throws Exception
     */
    @RequestMapping("likeComment")
    public void setLikeComment(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String comment = request.getParameter("comment_id");
        String user_id = request.getParameter("user_id");
        String access_token = request.getParameter("access_token");
        String like_state = request.getParameter("like_state");
        if (StringUtil.isEmpty(comment) || !StringUtil.isNumeric(comment)
                || StringUtil.isEmpty(user_id) || !StringUtil.isNumeric(user_id)
                || StringUtil.isEmpty(access_token)
                || StringUtil.isEmpty(like_state) || !StringUtil.isNumeric(like_state)) {
            JsonUtils.toErrorResult(request, response, "参数不正确");
            return;
        }
        UserdataDTO userdataDTO = new UserdataDTO();
        userdataDTO.setId(Long.valueOf(user_id));
        UserdataModel userdataModel = userdataService.getOne(userdataDTO);
        if (userdataModel == null || !access_token.equals(userdataModel.getAppToken())) {
            JsonUtils.toErrorResult(request, response, "请先登录!", OprationStatus.LOGIN.getCode());
            return;
        }

        CommentDTO commentDTO = new CommentDTO();
        commentDTO.setId(Integer.valueOf(comment));
        CommentModel commentModel = commentService.getOne(commentDTO);
        if (commentModel == null) {
            JsonUtils.toSuccessResult(request, response, "没有该评论", "");
            return;
        } else {
            if (commentModel.getCommentState() != CommentStateEnum.NORMAL.getCode()) {
                JsonUtils.toErrorResult(request, response, "该评论已经被删除!", OprationStatus.FAIL.getCode());
            } else {
                LikeCommentDTO likeCommentDTO = new LikeCommentDTO();
                likeCommentDTO.setCommentId(Integer.valueOf(comment));
                likeCommentDTO.setUserId(Integer.valueOf(user_id));
                LikeCommentModel likeCommentModel = likeCommentService.getOne(likeCommentDTO);
                if (likeCommentModel != null) {
                    likeCommentModel.setLikeState(Integer.valueOf(like_state));
                    likeCommentService.updateByPrimaryKey(likeCommentModel);
                    JsonUtils.toSuccessResult(request, response, "success", "");
                } else {
                    LikeCommentModel model = new LikeCommentModel();
                    model.setLikeState(Integer.valueOf(like_state));
                    model.setCommentId(Integer.valueOf(comment));
                    model.setUserId(Integer.valueOf(user_id));
                    model = likeCommentService.insert(model);
                    if (model != null) {
                        JsonUtils.toSuccessResult(request, response, "success", "");
                    } else {
                        JsonUtils.toErrorResult(request, response, "评论失败!", OprationStatus.FAIL.getCode());
                    }
                }
            }
        }
    }

    /**
     * comment_id  删除的评论id
     * user_id    用户给id
     * access_token  token
     *
     * @param request
     * @throws Exception
     */
    @RequestMapping("comment/delete")
    public void deleteComment(HttpServletRequest request) throws Exception {
        String comment = request.getParameter("comment_id");
        String user_id = request.getParameter("user_id");
        String access_token = request.getParameter("access_token");
        JSONObject result = new JSONObject();
        if (StringUtil.isEmpty(comment) || !StringUtil.isNumeric(comment)
                || StringUtil.isEmpty(user_id) || !StringUtil.isNumeric(user_id)
                || StringUtil.isEmpty(access_token)) {
            JsonUtils.toErrorResult(request, response, "参数不正确!", OprationStatus.FAIL.getCode());
            writeToJson(result);
            return;
        }
        UserdataDTO userdataDTO = new UserdataDTO();
        userdataDTO.setId(Long.valueOf(user_id));
        UserdataModel userdataModel = userdataService.getOne(userdataDTO);
        if (userdataModel == null || !access_token.equals(userdataModel.getAppToken())) {
            JsonUtils.toErrorResult(request, response, "请先登录!", OprationStatus.LOGIN.getCode());
        }
        CommentDTO commentDTO = new CommentDTO();
        commentDTO.setId(Integer.valueOf(comment));
        CommentModel commentModel = commentService.getOne(commentDTO);
        if (commentModel == null) {
            JsonUtils.toSuccessResult(request, response, "没有该评论!", "");
            return;
        } else {
            if (commentModel.getCommentState() != CommentStateEnum.NORMAL.getCode()) {
                JsonUtils.toErrorResult(request, response, "该评论已经被删除!", OprationStatus.FAIL.getCode());
                return;
            } else {
                try {
                    commentModel.setCommentState(CommentStateEnum.DELETE.getCode());
                    commentService.updateByPrimaryKey(commentModel);
                    JsonUtils.toSuccessResult(request, response, "删除成功!", "");
                } catch (Exception e) {
                    JsonUtils.toErrorResult(request, response, "操作失败!", OprationStatus.FAIL.getCode());
                }
            }
        }
    }


}
